<?php

declare (strict_types=1);

namespace app\store\service\client\wxofficial;

use app\common\library\helper;
use app\common\service\BaseService;
use app\store\model\h5\Setting as H5SettingModel;
use app\store\model\wxofficial\Setting as SettingModel;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

/**
 * 服务层：微信公众号设置
 * Class Setting
 * @package app\store\service\client\wxofficial
 */
class Setting extends BaseService
{
    /**
     * 获取微信公众号设置
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function basic(): array
    {
        $setting = $this->getSetting();
        return [
            'setting' => $setting,
            'domain' => $this->getDomain(),
            'serverUrl' => $this->getServerUrl(),
            'serverIP' => $this->getServerIP(),
        ];
    }

    /**
     * 获取微信公众号设置
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getSetting(): array
    {
        $model = new SettingModel;
        return $model->getBasic();
    }

    /**
     * 获取公众号端访问域名（实际上是H5实际访问地址）
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function getDomain(): string
    {
        $h5Url = H5SettingModel::getH5Url();
        $parse = parse_url($h5Url);
        return empty($parse['host']) ? '请先设置H5站点地址' : $parse['host'];
    }

    /**
     * 服务端接口url (token)
     * @return string
     */
    private function getServerUrl(): string
    {
        return helper::buildUrl('/api/wxofficial/serve');
    }

    /**
     * 服务器IP地址
     * @return string
     */
    private function getServerIP(): string
    {
        try {
            $content = file_get_contents('https://ip.3322.net/');
            if (!empty($content)) {
                $content = trim($content);
            }
            \validate()->check(['content' => $content], ['content' => 'ip']);
            return $content;
        } catch (\Throwable $e) {
        }
        return '未能获取IP';
    }
}